var param = {}, formId = 'queryOrderRefundForm', url = "/openx/afterSalse/queryService/listOrderRefund", days = 30,
    currOrderDetail = {}, currConutDownTime, setTimeoutId;

//获取当前月多少天
function getDaysByMonth(year, month) {
    var monthDays;
    //判断月份大小获得天数
    if (month == '1' || month == '3' || month == '5' || month == '7' || month == '8' || month == '10' || month == '12') {
        monthDays = 31;
    } else if (month == '4' || month == '6' || month == '9' || month == '11') {
        monthDays = 30;
    } else {
        monthDays = 28;
        //判断当前选择的年份是否是闰年
        if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) {
            monthDays = 29;
        }
    }
    days = monthDays;
    return days;
}

function DateToStr(date, flag) {
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString();
    var day = (date.getDate()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
//    var time='';
//    if(flag=='max'){time='23:59:59';}
//    if(flag=='min'){time='00:00:00';}
    dateTime = year + "-" + month + "-" + day;
    return dateTime;
}

var start = {
    istime: false,
    format: 'YYYY-MM-DD',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        end.min = datas; //开始日选好后，重置结束日的最小日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth() + 1)
        date.setDate(new Date(date.getDate() + (days - 1)));
        end.max = DateToStr(date, 'max');

    }
};
var end = {
    istime: false,
    format: 'YYYY-MM-DD',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        start.max = datas; //结束日选好后，重置开始日的最大日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth());
        days = days > date.getDate() ? days : date.getDate();
        date.setDate(new Date(date.getDate() - (days - 1)));
        start.min = DateToStr(date, 'min');
    }
};

$("#createStartTime").on("click", function () {
    start.elem = this;
    laydate(start);
});
$("#createEndTime").on("click", function () {
    end.elem = this;
    laydate(end);
});

//初始化时间
layui.use('laydate', function () {
    var laydate = layui.laydate;
    document.getElementById('createStartTime').value = laydate.now(-1);
    document.getElementById('createEndTime').value = laydate.now();

    var data = $.openx.getJsonObj(formId);

    if (data.createStartTime !== '') {
        data.createStartTime = data.createStartTime + " 00:00:00";
    }
    if (data.createEndTime !== '') {
        data.createEndTime = data.createEndTime + " 23:59:59";
    }
    param.form = data;
    $.openx.initTable("table", url, param);

});

/**
 * 剩余时间倒计时
 */
$($.openx.tableId).on('load-success.bs.table', function (e, rows, $element) {

    if (setTimeoutId != undefined) {
        clearTimeout(setTimeoutId);
    }
    showCountdownTime();
});

var showCountdownTime = function () {

    var allRows = $($.openx.tableId).bootstrapTable('getData');
    var allRowsCount = allRows.length;
    if (allRowsCount > 0) {
        for (var i = 0; i < allRowsCount; i++) {
            var obj = allRows[i];
            var createTime = obj.deadlineTime;
            var $td = $("#table tbody tr[data-index='" + i + "'] td.diycol");
            $($td).text(getTimeSub(createTime));
        }
    }
    $("#waitTime").html("剩余处理时间" + getTimeSub(currConutDownTime));
    if ((new Date(currConutDownTime)) - (new Date()) < 0) {
        $("#aduitBtn").hide();
    } else {
        $("#aduitBtn").show();
    }
    if (currConutDownTime == undefined) {
        $("#aduitBtn").hide();
    }
    setTimeoutId = setTimeout(showCountdownTime, 1000);
};

function getTimeSub(createTime) {
    var now = new Date();
    //结束时间不为空的时候，解析结束时间
    var flag = createTime === null || createTime === undefined || createTime === '' || (createTime + '').trim() === '';
    var countdownText = "";
    if (!flag) {
        var endTime = new Date(createTime);
        //计算时间差
        var timeDiff = endTime - now;

        if (timeDiff < 0) {
            countdownText += "00:00:00";
        } else {
            //计算出相差天数，小时，分钟，秒
            var days = Math.floor(timeDiff / (24 * 3600 * 1000));
            var leave1 = timeDiff % (24 * 3600 * 1000);
            var hours = Math.floor(leave1 / (3600 * 1000));
            var leave2 = leave1 % (3600 * 1000);
            var minutes = Math.floor(leave2 / (60 * 1000));
            var leave3 = leave2 % (60 * 1000);
            var seconds = Math.round(leave3 / 1000);

            if (days > 0) {
                hours = hours + days * 24;
            }
            if (hours > 0) {
                if (hours < 10) {
                    countdownText += "0" + hours + ":";
                } else {
                    countdownText += hours + ":";
                }
            } else {
                countdownText += "00:";
            }
            if (minutes > 0) {
                if (minutes < 10) {
                    countdownText += "0" + minutes + ":";
                } else {
                    countdownText += minutes + ":";
                }
            } else {
                countdownText += "00:";
            }
            if (seconds > 0) {
                if (seconds < 10) {
                    countdownText += "0" + seconds;
                } else {
                    countdownText += seconds;
                }
            } else {
                countdownText += "00";
            }
        }
    } else {
        countdownText = "00:00:00";
    }
    return countdownText;
}


//格式化订单详情按钮
function showOrderRefundDetailFormat(value, row) {
    return "<a href=\'javascript:void(0)\' onclick =\'javascript:showOrderRefundDetail(" + JSON.stringify(row) + ")\'><button type='button' class='btn btn-outline btn-primary btn-xs " + (row.bizCode == 'PICKUP_FAIL_CHECK' ? 'biz-code-css' : '') + "'>售后单详情</button> <a>";
}

//查询按钮触发
$.openx.query = function () {
    //查询验证时间区间
    var createStartTime = new Date($("#createStartTime").val().replace(/\-/g, "\/"));
    var createEndTime = new Date($("#createEndTime").val().replace(/\-/g, "\/"));
    if (createStartTime > createEndTime) {
        layer.msg('开始时间不能大于结束时间！');
        return false;
    }
    if (createStartTime.setDate(createStartTime.getDate() + days) < createEndTime) {
        layer.msg('选择的时间区间必须在' + days + '天以内');
        return false;
    }

    var data = $.openx.getJsonObj(formId);
    if (data.createStartTime !== '') {
        data.createStartTime = data.createStartTime + " 00:00:00";
    }
    if (data.createEndTime !== '') {
        data.createEndTime = data.createEndTime + " 23:59:59";
    }
    param.form = data;
    var equryTimeStamp = new Date();
    $.openx.tableRefresh(url + "?t=" + equryTimeStamp.getTime(), param);
}

function resetForm() {
    $('#queryOrderRefundForm')[0].reset();
    $('#channelSelectsId').val(null).trigger('change');
    var laydate = layui.laydate;
    document.getElementById('createStartTime').value = laydate.now(-1).split(' ')[0];
    document.getElementById('createEndTime').value = laydate.now().split(' ')[0];
    start.max = '2099-06-16';
    start.min = '1900-01-01';
    end.max = '2099-06-16';
    end.min = '1900-01-01';
    var data = $.openx.getJsonObj(formId);
    data.createStartTime = data.createStartTime + " 00:00:00";
    data.createEndTime = data.createEndTime + " 23:59:59";
    param.form = data;
    $.openx.initTable("table", url + "?t=" + new Date().getTime(), param);
}

// 点击订单状态查询订单信息
var previousObj = $("button[name='refundStatus']")[0];
$("button[name='refundStatus']").on('click', function (e) {
    var $this = e.currentTarget;
    $("input[name='refundStatus']").val($this.value);
    if (previousObj != $this) {
        $($this).find('i').addClass("glyphicon glyphicon-ok-sign")
        $(previousObj).find('i').removeClass('glyphicon glyphicon-ok-sign');
    }
    previousObj = $this;
    $.openx.query();
})


//查看订单详情
function showOrderRefundDetail(row) {
    $X("/afterSalse/queryService", "getOrderRefundDetail").callx({
        refundCode: row.refundCode,
        onResult: function (result) {

            layer.closeAll('loading');
            result.channelName = channelMap.get(result.topChannelCode);
            result.createTime = $.openx.formatDate(new Date(result.createTime));
            $.each(result.orderRefundList, function (index, val) {
                (result.orderRefundList)[index].createTime = $.openx.formatDate(new Date((result.orderRefundList)[index].createTime));

            });
            result.isPickupFail = row.bizCode == 'PICKUP_FAIL_CHECK' ? 'Y' : 'N';
            result.isShowNodeInfo = startWith(result.channelCode, "JDDJ") ? "Y" : "N";
            laytpl($.openx.innerHtml('orderRefundDetailTpl')).render(result, function (html) {
                $.openx.openLayer(null, '售后单详情', html, true)
            });
            //当前订单详细对象
            currOrderDetail = result;
            currConutDownTime = row.deadlineTime;
            $("#waitTime").html("剩余处理时间" + getTimeSub(currConutDownTime));

            if ((new Date(row.deadlineTime)) - (new Date()) < 0) {
                $("#aduitBtn").hide();
            } else {
                $("#aduitBtn").show();
            }
            if (currConutDownTime == undefined) {
                $("#aduitBtn").hide();
            }
            $("#otherRefuseReason").hide();
        },
        onError: function (error) {

        }
    });
}

function startWith(val, str) {

    if (str == null || str == "" || val.length == 0 || str.length > val.length) {
        return false;
    }

    if (val.substr(0, str.length) == str) {
        return true;
    } else {
        return false;
    }
}

function formatCode(value, row) {
    if (value && value!=='000000') {
        return '\'' + value;
    } else {
        return '';
    }
}

function topChannelFormat(value, row) {
    return channelMap.get(value);
}

//格式化下单时间
function createTimeFormat(value, row) {
    return $.openx.formatDate(new Date(value));
}


/**
 * 退货申请-拒绝
 * @param orderCode
 */
function refuseRefund(refundCode) {
    var refuseReasonCode = $("select[name='refuseReason'] option:selected").val();
    if (refuseReasonCode === '' || refuseReasonCode === undefined) {
        layer.msg("请选择拒绝原因！");
        return;
    }
    var refuseReason = $("select[name='refuseReason'] option:selected").text();
    if (refuseReasonCode === '99') {
        refuseReason = $("#otherRefuseReason").val();
        if (refuseReason === '' || refuseReason === null) {
            layer.msg("如果选择其他原因，请输入真实原因！");
            $("#otherRefuseReason").focus();
            return;
        }
    }

    thridReturnApplDeal(refundCode, "REFUSE_REFUND", refuseReason);
}

/**
 * 退货申请-同意-仅退款
 * @param orderCode
 */
function agreeRefund(refundCode) {
    thridReturnApplDeal(refundCode, "AGREE_REFUND", "");
}

/**
 * 退货申请-同意-退货退款
 * @param refundCode
 */
function agreeNeedBack(refundCode) {
    thridReturnApplDeal(refundCode, "AGREE_NEED_BACK", "");
}

/**
 * 退货申请-同意-仅退款（超时锁定，强制同意）
 * @param orderCode
 */
function agreeRefundForce(refundCode) {
    layer.confirm('该笔售后单，平台方已经超时默认同意退款，请核实具体情况！', {
        btn: ['确定']
        ,btn1: function(index, layero){
            thridReturnApplDeal(refundCode, "AGREE_REFUND", "");
        }
    });
}

/**
 * 退货申请-同意-退货退款
 * @param refundCode
 */
function agreeNeedBackForce(refundCode) {
    layer.confirm('该笔售后单，平台方已经超时默认同意退款，请核实具体情况!', {
        btn: ['确定']
        ,btn1: function(index, layero){
            thridReturnApplDeal(refundCode, "AGREE_NEED_BACK", "");
        }
    });
}


/**
 * 三方退货申请处理
 * @param orderCode 订单编号
 * @param dealCode 处理编码 1-拒绝 2-同意直接退款 3-同意需退货
 * @param refuseReason 拒绝原因
 */
function thridReturnApplDeal(refundCode, dealCode, refuseReason) {
    $X("/order/operateService", "thridReturnApplDeal").callx({
        refundCode: refundCode, dealCode: dealCode, refuseReason: refuseReason, remark: null,
        onResult: function (result) {
            if (result) {
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            } else {
                layer.msg("操作失败");
            }
        },
        onError: function (error) {
            layer.msg("操作失败" + JSON.parse(error).message);
        }
    });
}

/**
 * 退货入库按钮确认操作
 */
function refundOrderStockConfirm(refundCode) {
    $X("/order/queryService", "getOrderRefundByRefundCode").callx({
        refundCode: refundCode,
        onResult: function (result) {
            currOrderDetail.refundOrder = result;
            layer.closeAll('loading');
            /*laytpl($.openx.innerHtml('returnOrderFinalTpl')).render(currOrderDetail, function (html) {
                $.openx.openLayer(['940', '530'], '售后单详情', html, true)
            });*/
            laytpl($.openx.innerHtml('returnOrderFinalTpl')).render(currOrderDetail, function (html) {
                var index = $.openx.openLayer(['940', '530'], '确认退货申请', html, true, function () {
                    //确认操作
                    layer.confirm('请确认物品完好，是否退货入库？', {
                        btn: ['确认', '取消'] //按钮
                    }, function () {
                        doRefundOrderStock(refundCode);
                    }, function () {
                        layer.closeAll('loading');
                    });
                });
            });
        },
        //请求失败执行
        onError: function (error) {
            layer.msg(JSON.parse(error).message);
        }
    });
}

/**
 * t退货入库
 * @param orderCode
 */
function doRefundOrderStock(refundCode) {
    $X("/order/operateService", "refundOrderStorage").callx({
        refundCode: refundCode,
        onResult: function (result) {
            layer.msg('退货单处理成功', {time: 1000}, function () {
                layer.closeAll();
                //手动刷新表格
                $.openx.tableRefresh(null, null, true);
            });
        },
        onError: function (error) {
            layer.msg(JSON.parse(error).message);
        }
    });
}

function queryRefundLogistics() {
    var outRefundCode = currOrderDetail.orderRefundList[0].outRefundCode == undefined ? "" : currOrderDetail.orderRefundList[0].outRefundCode;
    $X("/logistics/logisticsListService", "getDeliveryTask").callx({
        orderCode: outRefundCode,
        onResult: function (result) {
            if (!result) {
                result = {};
            }
            layer.closeAll('loading')
            laytpl($.openx.innerHtml('refundLogisticsInfotpl')).render(result, function (html) {
                $.openx.openLayer(null, '物流跟踪详情', html, true);
            });
        },
        onError: function (error) {
            var res = JSON.parse(error);
            layer.msg(res.message)
        }
    });
}

//乘法函数
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    // alert(Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m));
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

function changeRefuseReason() {
    var refuseReasonCode = $("select[name='refuseReason'] option:selected").val();
    if (refuseReasonCode === '99') {
        $("#otherRefuseReason").show();
        return;
    }
    $("#otherRefuseReason").hide();
}